package controller

import (
	"errors"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEntity"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEntityManager"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedisStatus"
	"gitee.com/fierce_wolf/go-fox-edge-common/commSql"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Method"
	"gitee.com/fierce_wolf/go-fox-edge-common/edgeEntity"
	"gitee.com/fierce_wolf/go-fox-edge-common/httpserver"
	"go-fox-edge-kernel-manager/utils/PageUtils"
	"strconv"
	"strings"
)

type channelManageController struct {
}

func (e *channelManageController) init() {
	httpserver.Server.POST("/channel/entities", e.selectEntityList)
	httpserver.Server.POST("/channel/page", e.selectPageList)
	httpserver.Server.GET("/channel/entity", e.queryEntity)
	httpserver.Server.POST("/channel/entity", e.insertEntity)
	httpserver.Server.PUT("/channel/entity", e.updateEntity)
	httpserver.Server.DELETE("/channel/entity", e.deleteEntity)
	httpserver.Server.DELETE("/channel/entities", e.deleteEntityList)

	httpserver.Server.GET("/channel/types", e.queryChannelType)
}

func (e *channelManageController) selectEntityList(context httpserver.Context, body map[string]interface{}) (interface{}, error) {
	return e.selectList(context, body, false)
}

func (e *channelManageController) selectPageList(context httpserver.Context, body map[string]interface{}) (interface{}, error) {
	return e.selectList(context, body, true)
}

func (e *channelManageController) selectList(context httpserver.Context, body map[string]interface{}, isPage bool) (interface{}, error) {
	entityList := commEntityManager.FindEntityList(edgeEntity.Type.ChannelEntity.Type(), func(value commEntity.IEntity) bool {
		entity := value.(*edgeEntity.ChannelEntity)

		result := true

		if Map.Has(body, "channelName") {
			result = result && strings.Count(entity.ChannelName, body["channelName"].(string)) > 0
		}
		if Map.Has(body, "channelType") {
			result = result && entity.ChannelType == body["channelType"]
		}

		return result
	})

	// 获得分页数据
	if isPage {
		return PageUtils.GetPageList(entityList, body), nil
	} else {
		return commEntity.BuildMapList(entityList), nil
	}
}

func (e *channelManageController) queryChannelType(context httpserver.Context) (interface{}, error) {
	channelTypes := make(map[string]interface{})

	// 正在运行的channel类型的进程
	processList := commRedisStatus.GetDataList(60 * 1000)
	for _, process := range processList {
		modelType := process["modelType"]
		if modelType != "channel" {
			continue
		}

		modelName := process["modelName"]
		if modelType == nil || modelType == "" {
			continue
		}

		channelTypes[modelName.(string)] = nil
	}

	// 到数据库中查找同类数据：历史上启动过，但现在停止运行的channel进程
	optionList, err := commSql.Fox.SelectOption1List("tb_channel", "channel_type", false)
	if err != nil {
		return nil, err
	}

	for _, process := range optionList {
		channelType := process["channel_type"]
		if Method.HasEmpty(channelType) {
			continue
		}

		channelTypes[channelType.(string)] = nil
	}

	return Map.GetKeys(channelTypes), nil
}

func (e *channelManageController) queryEntity(context httpserver.Context) (interface{}, error) {
	str := context.Query("id")
	if str == "" {
		return nil, errors.New("输入的id为null")
	}

	id, err := strconv.ParseInt(str, 10, 64)
	if err != nil {
		return nil, err
	}

	exist := commEntityManager.GetEntityById(edgeEntity.Type.ChannelEntity.Type(), id)
	if exist == nil {
		return nil, errors.New("实体不存在")
	}

	return commEntity.BuildMap(exist), nil
}

func (e *channelManageController) insertEntity(context httpserver.Context, body map[string]interface{}) (interface{}, error) {
	delete(body, "id")
	return e.insertOrUpdate(context, body)
}

func (e *channelManageController) updateEntity(context httpserver.Context, body map[string]interface{}) (interface{}, error) {
	return e.insertOrUpdate(context, body)
}

func (e *channelManageController) insertOrUpdate(context httpserver.Context, body map[string]interface{}) (interface{}, error) {
	// 提取业务参数
	channelName := Map.GetString(body, "channelName", "")
	channelType := Map.GetString(body, "channelType", "")
	channelParam := Map.GetMap(body, "channelParam", nil)
	extendParam := Map.GetMap(body, "extendParam", nil)

	// 简单校验参数
	if Method.HasEmpty(channelName, channelType) || Method.HasNull(channelParam, extendParam) {
		return nil, errors.New("参数不能为空:channelType, channelName, channelParam, extendParam")
	}

	// 构造作为参数的实体
	entity := edgeEntity.Type.ChannelEntity.Instance()
	entity.ChannelType = channelType
	entity.ChannelName = channelName
	entity.ChannelParam = channelParam
	entity.ExtendParam = extendParam

	// 新增/修改实体：参数不包含id为新增，包含为修改
	if !Map.Has(body, "id") {
		exist, err := commEntityManager.GetEntityByServiceKey(entity.Type(), entity.MakeServiceKey())
		if err != nil {
			return nil, err
		}
		if exist != nil {
			return nil, errors.New("实体已存在")
		}

		err = commEntityManager.InsertEntity(entity)
		if err != nil {
			return nil, err
		}

		return nil, nil
	} else {
		id := Map.GetInt64(body, "id", 0)

		exist := commEntityManager.GetEntityById(entity.Type(), id)
		if exist == nil {
			return nil, errors.New("实体不存在")
		}

		// 修改数据
		entity.BaseEntity.Id = id
		entity.GetBaseEntity().CreateTime = exist.GetBaseEntity().CreateTime
		entity.GetBaseEntity().UpdateTime = exist.GetBaseEntity().UpdateTime
		return nil, commEntityManager.UpdateEntity(entity)
	}
}

func (e *channelManageController) deleteEntity(context httpserver.Context) (interface{}, error) {
	str := context.Query("id")
	if str == "" {
		return nil, errors.New("输入的id为null")
	}

	id, err := strconv.ParseInt(str, 10, 64)
	if err != nil {
		return nil, err
	}

	exist := commEntityManager.GetEntityById(edgeEntity.Type.ChannelEntity.Type(), id)
	if exist == nil {
		return nil, errors.New("实体不存在")
	}

	err = commEntityManager.DeleteEntity(exist)
	if err != nil {
		return nil, err
	}

	return commEntity.BuildMap(exist), nil
}

func (e *channelManageController) deleteEntityList(context httpserver.Context) (interface{}, error) {
	ids := context.Query("ids")

	idList := strings.Split(ids, ",")
	for _, str := range idList {
		if str == "" {
			continue
		}
		id, err := strconv.ParseInt(str, 10, 64)
		if err != nil {
			return nil, err
		}

		exist := commEntityManager.GetEntityById(edgeEntity.Type.ChannelEntity.Type(), id)
		if exist == nil {
			return nil, errors.New("实体不存在")
		}

		err = commEntityManager.DeleteEntity(exist)
		if err != nil {
			return nil, err
		}
	}

	return nil, nil
}
